<!--
 * @轮子的作者: 轮子哥
 * @Date: 2023-07-04 15:34:18
 * @LastEditTime: 2023-12-08 15:49:04
-->
<template>
    <div>
        <div @click="handClick" :style="showStyle" class="radioSelect">
            <span style="float: left;">{{ leftText }}</span>
            <span class="right_T">
                {{ nowSelectName }}
                <img src="../../assets/images/upRow.svg">
            </span>
        </div>

        <div class="popup" v-if="show" :style="popupStyle">
            <!--标题-->
            <div v-if="isShowTitle" class="topTitle">
                <div @click="show = !show" style="white-space: nowrap;" v-if="!isClickSearch">
                    {{ $t('text.DialogLayout.l22') }}
                </div>
                <div @click="isClickSearch = !isClickSearch" style="white-space: nowrap;" v-if="isClickSearch">{{
                    $t('text.Common.l40') }}</div>
                <div style="color: black;">{{ leftText }}</div>
                <div @click="confirm" style="white-space: nowrap;">{{ $t('text.DialogLayout.l23') }}</div>
            </div>

            <!--普通搜索框-->
            <div class="df" v-if="isShowSerach1">
                <img class="img1" src="../../assets/images/search2.png" @click="search" />
                <input :placeholder="$t('text.House.l151')" class="leftTop2Input" v-model="searchText" @click="searchClick"
                    @keyup.enter="search">
            </div>

            <!--双范围搜索框-->
            <div class="dff" v-if="isShowSerach2">
                <div class="dfc">
                    <div class="dff">
                        <div class="inputEndText">{{ inputEndText }}</div>
                        <input :placeholder="$t('text.House.l151')" class="searchInput" v-model="input1" type="number"
                            oninput="value=value.replace(/[^0-9]/g,'')">
                    </div>
                    <div class="hitText"> {{ input1Hit }}</div>
                </div>
                <div>-</div>

                <div class="dfc">
                    <div class="dff">
                        <div class="inputEndText">{{ inputEndText }}</div>
                        <input :placeholder="$t('text.House.l151')" class="searchInput" v-model="input2" type="number"
                            oninput="value=value.replace(/[^0-9]/g,'')">
                    </div>
                    <div class="hitText"> {{ input2Hit }}</div>
                </div>
            </div>

            <!--固定两个扩展/房源角色/人员范围-->
            <div v-if="isRange">
                <div class="item_name2" v-for="(s, index) in rangeList" v-bind:key="s">

                    <div class="item_name_left">
                        <div v-if="s.dictName === nowSelectName" class="item_name_default">{{ s.dictName }}</div>
                        <div v-else>{{ isCustomer && index == 0 ? $t('text.Common.l59') : s.dictName }}</div>
                    </div>

                    <!--子集点扩展-->
                    <div v-if="s.children != undefined" style="flex: 0.5;">
                        <RadioSelectNext v-if="index == 0" :selectList="selectListCopy" :leftText="leftText" :index="-1"
                            :position="position" @returnData="getSelect">
                            <div class="item_name_right">{{ childerDefault1 }}＞</div>
                        </RadioSelectNext>
                        <RadioSelectNext v-if="index == 1" :selectList="orgTreeList" isShowSerach1 :leftText="leftText"
                            :position="position" :index="-2" @returnData="getSelect">
                            <div class="item_name_right">{{ childerDefault2 }}＞</div>
                        </RadioSelectNext>
                    </div>
                </div>
            </div>

            <!--多选数据列表选择-->
            <div class="ov" v-show="!isClickSearch && isMultiple">
                <div class="item_name" v-for="(s, index) in selectListCopy" v-bind:key="s">
                    <div @click="multipleItem(s, index)" style="flex: 1;">
                        <div v-if="multipleList.includes(s.dictValue)" class="item_name_default">
                            <span>{{ s.dictName }}</span>
                            <span style="float: right;">✔</span>
                        </div>
                        <div v-else>{{ s.dictName }}</div>
                    </div>
                </div>
            </div>

            <!--搜索数据列表-->
            <div v-show="isClickSearch && !isMultiple" class="ov">
                <div v-if="searchText == ''">
                    <div class="historyText">
                        <span style="text-align: left;">{{ $t('text.Common.l32') }}</span>
                        <span style="text-align: right;color: #6698ff;" @click="clearLocal">{{ $t('text.Common.l33')
                        }}</span>
                    </div>
                    <div class="item_name" v-for="s in searchTextTemp" v-bind:key="s" @click="searchText = s">
                        {{ s }}
                    </div>
                </div>
                <div v-else>
                    <div class="item_name" v-for="s in areaList" v-bind:key="s" @click="getSelect(s.dictName, s.dictValue,0,s)">
                        <div v-if="s.dictName === nowSelectName" class="item_name_default">{{ s.dictName }}</div>
                        <div v-else>{{ s.dictName }}</div>
                    </div>
                </div>
            </div>

            <!--地区数据列表选择-->
            <div class="ov" v-if="isArea && !isClickSearch && !isMultiple">
                <div class="item_name2" v-for="(s, index) in selectListCopy" v-bind:key="s">
                    <div @click="getSelect(s.dictName, s.id,0,s)" class="item_name_left">
                        <div v-if="s.dictName === nowSelectName" class="item_name_default">{{ s.dictName }}</div>
                        <div v-else>{{ s.dictName }}</div>
                    </div>

                    <!--子集点扩展-->
                    <div v-if="s.hasChildren" style="flex: 0.5;">
                        <RadioSelectNext :selectList="s.children" isShowSerach1 :leftText="leftText" @returnData="getSelect"
                            :position="position" :index="index">
                            <div class="item_name_right">{{ childerDefaultIndex == index ? childerDefault : '' }}＞</div>
                        </RadioSelectNext>
                    </div>
                </div>
            </div>

            <div v-if="isRange2">
                <div class="item_name2" v-for="s in selectListCopy" v-bind:key="s">

                    <div class="item_name_left" @click="getSelect(s.dictName, s.dictValue, 2, s)">
                        <div v-if="s.dictName === nowSelectName" class="item_name_default">{{ s.dictName }}</div>
                        <div v-else>{{ s.dictName }}</div>
                    </div>

                    <!--子集点扩展-->
                    <div v-if="s.children != undefined" style="flex: 0.5;">
                        <RadioSelectNext :selectList="s.children" :leftText="leftText" :index="2" @returnData="getSelect"
                            :position="position">
                            <div class="item_name_right">{{ childerDefault1 }}＞</div>
                        </RadioSelectNext>
                    </div>
                </div>
            </div>


            <!--数据列表选择-->
            <div v-if="isSingle">
                <div class="item_name" v-for="(s, index) in selectListCopy" v-bind:key="s">
                    <div @click="selectItem(s)" style="flex: 1;">
                        <div v-if="s.dictName === nowSelectName" class="item_name_default">{{ s.dictName }}</div>
                        <div v-else>{{ s.dictName }}</div>
                    </div>
                    <div v-if="s.child" class="item_name_right">
                        <RadioSelectNext :selectList="s.data.data" :isShowSerach1="s.data.isShowSerach1"
                            :leftText="leftText" :isShowSerach2="s.data.isShowSerach2" :index="index" :position="position"
                            @returnData="getSelect" :inputEndText="s.data.inputEndText">
                            {{ s.data.default }}＞
                        </RadioSelectNext>
                    </div>
                </div>
            </div>

            <!--底部确认框-->
            <div class="b1" style="justify-content: space-between;" v-if="isShowBottom">
                <el-button style="width: 70px;height: 25px;color: #6698ff;border-color: #6698ff;font-size: 12px;" plain
                    @click="bottomNoLimt">{{ $t('text.Common.l30') }}</el-button>
                <el-button type="primary" style="font-size: 12px;width: 70px;height: 25px;" @click="bottomConFirm">{{
                    $t('text.Common.l31') }}</el-button>
            </div>

        </div>
    </div>

    <div class="overlay" v-if="show" @click="handClick"></div>
</template>
  
<script >
import RadioSelectNext from './RadioSelectNext.vue'
import { ElMessage } from "element-plus"

export default {
    name: 'RadioSelect',
    emits: ['returnData', 'clearData'],
    props: {
        isShowTitle: Boolean,   //是否显示标题
        isRange: Boolean,       //是否是固定的房源角色/人员范围
        isRange2:Boolean,       //是否是人员范围
        isShowBottom: Boolean,  //是否显示底部的不限、确定,必须配合多选
        isMultiple: Boolean,    //是否多选列表
        isShowSerach1: Boolean, //是否有一个普通搜索框
        isShowSerach2: Boolean, //是否有一个双范围的输入搜索框，必须配合显示标题否则无意义
        isSingle: Boolean,      //是否是一个普通数据列表
        isArea: Boolean,        //是否是一个地区数据列表
        leftText: String,       //左侧标题
        isCustomer: Boolean,
        selectList: {           //数据列表的数据
            default: []
        },
        isResetList: Boolean,   //重置数据列表的数据
        searchKey: String,      //返回的字段名字
        isReset: Boolean,       //是否重置
        fastSearch: {           //回填快速搜索
            default: '',
            type: String,
        },
        orgTreeList: {          //人员范围的组织列表数据
            default: []
        },
        popupStyle: Object,     //自定义弹框样式
        showStyle: Object,       //一开始未打开的标题图案显示样式
        inputEndText: String,   //双范围的输入搜索框右侧默认单位提示值
        min: Number,            //最小值
        max: Number,            //最大值
        retuenAll: Boolean      //选择的列表是否把一整个item都返回，多选、输入框、房源角色/人员范围 无效
    },
    components: {
        RadioSelectNext: RadioSelectNext
    },
    data() {
        return {
            show: false,
            nowSelectName: this.selectList != null && this.selectList.length > 0 ? this.isRange ? this.$t('text.Common.l64') : this.selectList[0].dictName : '',
            selectListCopy: this.selectList,
            rangeList: [
                { "dictValue": "", "dictName": this.$t('text.Common.l28'), "children": [] },
                { "dictValue": "", "dictName": this.$t('text.Common.l29'), "children": [] }
            ],
            childerDefault1: '',
            childerDefault2: '',
            childerId: '',
            position: ["", ""],
            isClickSearch: false,
            searchText: "",
            searchTextTemp: [],
            input1: "",
            input2: "",
            input1Hit: "",
            input2Hit: "",
            multipleList: [],
            childerDefault: "",
            areaList: [],
            childerDefaultIndex: -1,
        }
    },
    mounted() {
        if (this.fastSearch != '') {
            if (this.searchKey == "roomNumber") {
                this.multipleList = this.fastSearch.split(",")?.filter(v => v !== this.$t('text.Common.l12'))
                this.nowSelectName = this.fastSearch
            } else {
                this.nowSelectName = this.fastSearch
            }
        } else {
            if (this.selectList && this.selectList.length > 0)
                this.nowSelectName = this.selectList.length > 0 ? this.isRange ? this.$t('text.Common.l64') : this.selectList[0].dictName : ''
        }
    },
    methods: {
        handClick() {
            this.show = !this.show
            if (this.show)
                this.$nextTick(() => {
                    const popupEl = document.querySelector('.popup');

                    // 如果找到了弹出框元素
                    if (popupEl) {
                        this.position = [popupEl.getBoundingClientRect().top, popupEl.getBoundingClientRect().right + 5]
                        // 计算弹出框底部距离窗口底部的距离
                        const bottomDist = popupEl.getBoundingClientRect().bottom - window.innerHeight;
                        // 如果底部距离小于弹出框高度，说明弹出框被遮挡，需要向上移动
                        if (bottomDist > 0) {
                            // 修改弹出框的样式，将其向上移动
                            popupEl.style.marginTop = `-${popupEl.getBoundingClientRect().height + 15}px`;
                        } else {
                            // 如果不被遮挡，清除样式，恢复原位置
                            popupEl.style.marginTop = '20px';
                        }
                    }
                })
        },
        selectItem(s) {
            if (!s.child) {
                if (String(s.dictValue) === "-999") {
                    this.$emit("clearData", { [this.searchKey]: "" })
                    this.$emit("returnData", { topFloor_EQ: "1" })
                    this.nowSelectName = s.dictName
                    this.show = !this.show
                } else {
                    //文本替换
                    this.nowSelectName = s.dictName
                    //先置空前置
                    let tempKey = this.searchKey
                    let tempValue = s.dictValue
                    let temp = { [tempKey]: this.retuenAll ? s : tempValue }
                    let temps = { [tempKey]: "", [tempKey + "_EQ"]: "", [tempKey + "_BEGIN"]: "", [tempKey + "_END"]: "", topFloor_EQ: "" }
                    this.$emit("clearData", temps)
                    //判断是否包含指定标识
                    if (s.dictValue.includes("_END")) {
                        //小于某个区间选择
                        tempKey = tempKey + "_END"
                        tempValue = tempValue.replace("_END", "")
                        temp = { [tempKey]: tempValue }
                    } else if (s.dictValue.includes("_BEGIN")) {
                        //大于某个区间选择
                        tempKey = tempKey + "_BEGIN"
                        tempValue = tempValue.replace("_BEGIN", "")
                        temp = { [tempKey]: tempValue }
                    } else if (s.dictValue.includes("-")) {
                        //双区间选择
                        const parts = s.dictValue.split("-")
                        temp = { [tempKey + "_BEGIN"]: parts[0], [tempKey + "_END"]: parts[1] }
                    }
                    if (s.dictValue != -1) {
                        //如果不是不限
                        this.$emit("returnData", temp)
                    }
                    this.show = !this.show
                }
            }
        },

        getSelect(name, value, index = 0, s) {
            if (value == null) {
                return
            }
            if (index == -1) {
                this.childerDefault1 = name
                this.nowSelectName = this.childerDefault2 == '' ? name + "-" + this.$t('text.Common.l66') : name + "-" + this.childerDefault2
                if (value != -1) {
                    const temp = { [this.searchKey.split(",")[0]]: value }
                    this.$emit('returnData', temp)
                } else {
                    const temp = { [this.searchKey.split(",")[0]]: '' }
                    this.$emit('clearData', temp)
                }
                this.show = !this.show
            }
            if (index == -2) {
                this.childerDefault2 = name
                this.childerId = value
                this.nowSelectName = this.childerDefault1 == '' ? this.$t('text.Common.l65') + "-" + name : this.childerDefault1 + "-" + name
                const temp = { [this.searchKey.split(",")[1] + "_LIKE_RIGHT"]: value, 'orgLevel': s.orgLevel }
                this.$emit('returnData', temp)
                this.show = !this.show
            }
            if (index >= 0) {
                this.childerDefault = name
                this.childerDefaultIndex = index
                this.childerId = value
                this.nowSelectName = name
                this.$emit("returnData", { [this.searchKey]:this.retuenAll ? s: this.childerId })
                this.show = !this.show
            }
        },

        //多选
        multipleItem(s) {
            if (this.multipleList.includes(s.dictValue)) {
                //如果已经选择了，再次点击取消删除列表
                this.multipleList = this.multipleList.filter((item) => item !== s.dictValue)
            } else {
                //没有选择，直接添加
                this.multipleList.push(s.dictValue)
            }
        },
        //底部选择不限
        bottomNoLimt() {
            this.nowSelectName = this.$t("text.Common.l30")
            let temps = { [this.searchKey]: "" }
            this.multipleList = []
            this.$emit("clearData", temps)
            this.show = !this.show
        },
        //底部选择确认
        bottomConFirm() {
            if (this.multipleList.length != 0) {
                this.nowSelectName = this.selectListCopy.filter(v=>this.multipleList.includes(v.dictValue)).map(item=>{return item.dictName}).join()
            } else {
                this.nowSelectName = this.$t("text.Common.l30")
            }
            let temp = { [this.searchKey]: this.multipleList.join() }
            this.$emit("returnData", temp)
            this.show = !this.show
        },

        //点击搜索
        searchClick() {
            //点击搜索之后再拿缓存，不在初始化拿
            const temp = localStorage.getItem(this.leftText)
            if (temp != null) {
                this.searchTextTemp = JSON.parse(temp)
            }
            this.isClickSearch = true
        },
        //根据字典数据进行模糊匹配
        searchByValue(data, value) {
            const result = []
            // 模糊匹配的逻辑
            function fuzzyMatch(str, searchValue) {
                const pattern = new RegExp(searchValue, "i") // 忽略大小写
                return pattern.test(str)
            }
            // 递归遍历数据并匹配
            function recursiveSearch(arr) {
                for (const item of arr) {
                    if (fuzzyMatch(item.dictName, value)) {
                        result.push({ dictName: item.dictName, dictValue: item.dictValue })
                    }
                    if (item.children && item.children.length > 0) {
                        recursiveSearch(item.children) // 递归遍历子节点
                    }
                }
            }
            recursiveSearch(data)
            return result
        },

        //搜索
        search() {
            //缓存搜索内容
            this.searchTextTemp.unshift(this.searchText)
            const tempLength = this.searchTextTemp.length
            if (tempLength > 5) {
                this.searchTextTemp.pop()
            }
            localStorage.setItem(this.leftText, JSON.stringify(this.searchTextTemp))
        },

        //清除搜索历史
        clearLocal() {
            localStorage.removeItem(this.leftText)
            this.searchTextTemp = []
        },

        //快速搜索获取标题和当前选中值
        returnFastSearch() {
            if (this.selectList[0].dictName != this.nowSelectName && this.nowSelectName != this.$t('text.Common.l64'))
                return { title: this.leftText, value: this.nowSelectName, searchKey: this.searchKey }
        },

        //确认按钮
        confirm() {
            if (this.isShowSerach2) {
                if (this.input1Hit == "" && this.input2Hit == "" && this.input1 !== "" && this.input2 !== "") {
                    const temp = { [this.searchKey + "_BEGIN"]: this.input1, [this.searchKey + "_END"]: this.input2 }
                    this.nowSelectName = this.input1 + this.inputEndText + " - " + this.input2 + this.inputEndText
                    this.$emit("returnData", temp)
                    this.show = !this.show
                } else {
                    ElMessage.error({
                        showClose: true,
                        message: this.$t("text.Common.l34"),
                        type: "error",
                    })
                }
            } else {
                this.show = !this.show
            }
        }
    },
    watch: {
        show: {
            handler(newValue) {
                if (!newValue) {
                    this.isClickSearch = false
                    this.selectListCopy = this.selectList
                }
            },
        },
        input1: {
            handler(newValue) {
                if (newValue !== "" && this.input2 !== "" && newValue > this.input2 && this.input2Hit == "") {
                    this.input1Hit = this.$t("text.Common.l35")
                } else if (newValue < this.min) {
                    this.input1Hit = this.$t("text.Common.l37") + this.min
                } else if (newValue > this.max) {
                    this.input1Hit = this.$t("text.Common.l38") + this.max
                } else {
                    this.input1Hit = ""
                }
                if (this.input2Hit != "" && newValue <= this.input2) {
                    this.input2Hit = ""
                }
            },
        },
        input2: {
            handler(newValue) {
                if (this.input1 !== "" && newValue !== "" && newValue < this.input1 && this.input1Hit == "") {
                    this.input2Hit = this.$t("text.Common.l39")
                } else if (newValue < this.min) {
                    this.input2Hit = this.$t("text.Common.l37") + this.min
                } else if (newValue > this.max) {
                    this.input2Hit = this.$t("text.Common.l38") + this.max
                } else {
                    this.input2Hit = ""
                }
                if (this.input1Hit != "" && newValue >= this.input1) {
                    this.input1Hit = ""
                }
            },
        },
        //重置数据列表
        isResetList() {
            if (this.searchKey == "houseDetailsType") {
                this.selectListCopy = this.selectList
                this.nowSelectName = this.$t("text.Common.l63")
            }
        },
        searchText: {
            handler() {
                this.areaList = this.searchByValue(this.selectListCopy, this.searchText)
            },
        },
        isReset: {
            handler() {
                this.nowSelectName = this.isRange ? this.$t('text.Common.l64') : this.selectList[0]?.dictName
            }
        },
        selectList() {
            this.nowSelectName = this.selectList != null && this.selectList.length > 0 ? this.isRange ? this.$t('text.Common.l64') : this.selectList[0].dictName : ''
            this.selectListCopy = this.selectList
        },

    },
    computed: {

    }

}

</script>

<style scoped>
.radioSelect {
    position: relative;
}

.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
}

.popup {
    position: absolute;
    background: white;
    border: 1px solid #eee;
    box-shadow: 1px 1px 15px #e5e5e5;
    z-index: 1;
    font-size: 13px;
    margin-top: 20px;
    margin-left: 25px;
    min-width: 225px;
    max-height: 275px;
    overflow: auto;
}

.right_T {
    float: right;
    color: black;
    display: flex;
    align-items: center;
}

img {
    width: 10px;
    height: 10px;
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);
    padding-left: 5px;
}

.topTitle {
    display: flex;
    justify-content: space-between;
    color: #6698ff;
    padding-left: 10px;
    padding-right: 10px;
    font-size: 12px;
    padding-top: 6px;
    padding-bottom: 6px;
    background-color: rgb(242, 242, 242);
    flex: 1;
}

.item_name {
    text-align: left;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
    color: black;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 5px;
}

.item_name2 {
    text-align: left;
    padding-top: 5px;
    padding-bottom: 5px;
    color: black;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 5px;
}

.item_name:hover {
    background-color: rgb(245, 247, 250);
}

.item_name_default {
    color: #6698ff;
}

.item_name_right {
    text-align: end;
    padding-right: 10px;
    padding-left: 25px;
    padding-top: 3px;
    padding-bottom: 3px;
    color: #6698ff;
    white-space: nowrap;
}

.item_name_left {
    flex: 1;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
}

.item_name_right:hover {
    background-color: rgb(245, 247, 250);
}

.item_name_left:hover {
    background-color: rgb(245, 247, 250);
}

.item_name_default:hover {
    background-color: rgb(245, 247, 250);
}

.df {
    display: flex;
    flex-direction: column;
}

.dff {
    display: flex;
    position: relative;
}

.dfc {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}





.hitText {
    color: red;
    font-size: 12px;
    font-weight: 100;
}

.ov {
    width: 225px;
    min-height: 180px;
    max-height: 200px;
    overflow: auto;
}

.right_TR {
    float: right;
    color: #FFC107;
    display: flex;
    align-items: center;
}

.img2 {
    width: 10px;
    height: 10px;
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);
    padding-left: 5px;
}

.searchInput {
    width: 100%;
    outline: none;
    height: 20px;
    padding-left: 8px;
    padding-right: 25px;
    border-radius: 5px;
    font-size: 12px;
    background: rgb(242, 242, 242);
    border: none;
    margin: 3px 10px;
}

.inputEndText {
    position: absolute;
    z-index: 2;
    color: rgb(168, 168, 168);
    font-size: 12px;
    right: 12px;
    top: 5px;
}

.img1 {
    position: absolute;
    width: 15px;
    height: 15px;
    top: 40px;
    z-index: 1;
    right: 25px;
    transform: rotate(0deg);
}

.leftTop2Input {
    outline: none;
    height: 25px;
    border: 1px solid rgb(220, 223, 230);
    padding-left: 8px;
    padding-right: 20px;
    border-radius: 5px;
    font-size: 12px;
    position: relative;
    margin: 5px 7px;
}

.leftTop2Input:focus {
    border: 1px solid #6698ff;
}

.historyText {
    font-size: 12px;
    color: gray;
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 10px;
}

.b1 {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    margin-left: 10px;
    margin-right: 10px;
    padding-bottom: 6px;
    border-top: 1px solid #ddd;
    padding-top: 6px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

input[type="number"] {
    -moz-appearance: textfield;
    appearance: none;
}
</style>
  